//
//  TYAlertController.m
//  Somago
//
//  Created by yqc on 2021/12/13.
//  Copyright © 2021 juniu. All rights reserved.
//

#import "TYAlertController.h"
#import "UIColor+TYColor.h"
#import "Masonry.h"
@interface TYAlertController ()

@property (nonatomic,copy) NSString * titleContent;//标题
@property (nonatomic,copy) NSString * textContent;//内容

@property (nonatomic,retain) NSAttributedString * titleAttrContent;
@property (nonatomic,retain) NSAttributedString * textAttrContent;

@end

@implementation TYAlertController

+ (instancetype)alertWithTitle:(NSString * _Nullable)title text:(NSString * _Nullable)text {
    TYAlertController * vc = [[TYAlertController alloc]init];
    vc.titleLabel.text = title;
    vc.textLabel.text = text;
    vc.modalPresentationStyle = UIModalPresentationCustom;
    vc.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
    vc.titleContent = title;
    vc.textContent = text;
    vc.lineColor = [UIColor colorWithHex:0xE8E8E8];
    return vc;
}

+ (instancetype)alertWithAttributedTitle:(NSAttributedString * _Nullable)title attributedText:(NSAttributedString * _Nullable)text {
    TYAlertController * vc = [[TYAlertController alloc]init];
    vc.titleLabel.attributedText = title;
    vc.textLabel.attributedText = text;
    vc.modalPresentationStyle = UIModalPresentationCustom;
    vc.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
    vc.titleAttrContent = title;
    vc.textAttrContent = text;
    vc.lineColor = [UIColor colorWithHex:0xE8E8E8];
    return vc;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    if (self.navigationController) {
        [self.navigationController setNavigationBarHidden:YES];
    }
    self.view.backgroundColor = [UIColor colorWithHex:0x000000 alpha:0.65];
    [self show];
    
}

- (NSMutableArray<TYAlertAction *> *)actionArray {
    if (!_actionArray) {
        _actionArray = [[NSMutableArray alloc]init];
    }
    return _actionArray;
}

- (void)addAction:(TYAlertAction *)action {
    if ([self.actionArray containsObject:action]) {
        [self.actionArray removeObject:action];
    }
    action.targetVC = self;
    [self.actionArray addObject:action];
}

- (NSMutableArray<TYAlertField *> *)fieldArray {
    if (!_fieldArray) {
        _fieldArray = [[NSMutableArray alloc]init];
    }
    return _fieldArray;
}

- (void)addTextField:(TYAlertField *)textField {
    if ([self.fieldArray containsObject:textField]) {
        [self.fieldArray removeObject:textField];
    }
    textField.targetVC = self;
    [self.fieldArray addObject:textField];
}

- (UILabel *)titleLabel {
    if (!_titleLabel) {
        _titleLabel = [[UILabel alloc]init];
        _titleLabel.textColor = [UIColor colorWithHex:0x000000];
        _titleLabel.font = [UIFont systemFontOfSize:16];
        _titleLabel.textAlignment = NSTextAlignmentCenter;
    }
    return _titleLabel;
}

- (UILabel *)textLabel {
    if (!_textLabel) {
        _textLabel = [[UILabel alloc]init];
        _textLabel.textColor = [UIColor colorWithHex:0x000000];
        _textLabel.font = [UIFont systemFontOfSize:16];
        _textLabel.textAlignment = NSTextAlignmentCenter;
        _textLabel.numberOfLines = 0;
    }
    return _textLabel;
}

- (UIView *)backgroundView {
    if (!_backgroundView) {
        _backgroundView = [[UIView alloc]init];
        _backgroundView.backgroundColor = [UIColor whiteColor];
        _backgroundView.layer.cornerRadius = 8;
        _backgroundView.layer.masksToBounds = YES;
    }
    return _backgroundView;
}

- (void)show {
    __weak typeof(self) weakSelf = self;
    [self.view addSubview:self.backgroundView];
    while (self.backgroundView.subviews.count) {
        [self.backgroundView.subviews.lastObject removeFromSuperview];
    }
    [self.backgroundView addSubview:self.titleLabel];
    [self.backgroundView addSubview:self.textLabel];
    
    if (self.titleLabel.text.length > 0) {
        [self.titleLabel mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.top.mas_equalTo(weakSelf.backgroundView).offset(12);
            make.left.mas_equalTo(weakSelf.backgroundView);
            make.right.mas_equalTo(weakSelf.backgroundView);
            make.height.mas_equalTo(35);
        }];
        
    }else {
        [self.titleLabel mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.top.mas_equalTo(weakSelf.backgroundView).offset(20);
            make.left.mas_equalTo(weakSelf.backgroundView).offset(10);
            make.right.mas_equalTo(weakSelf.backgroundView).offset(-10);
            make.height.mas_equalTo(0);
        }];
          
    }
    
    if (self.textLabel.text.length > 0) {
        NSDictionary *arrts = @{NSFontAttributeName:self.textLabel.font};
        CGSize size = [self.textLabel.text boundingRectWithSize:CGSizeMake([UIScreen mainScreen].bounds.size.width - 36*2, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin attributes:arrts context:nil].size;
        if (self.textAttrContent) {
            size = [self.textAttrContent boundingRectWithSize:CGSizeMake([UIScreen mainScreen].bounds.size.width - 36*2, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin context:nil].size;
        }
        [self.textLabel mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.left.mas_equalTo(weakSelf.backgroundView).offset(16);
            make.right.mas_equalTo(weakSelf.backgroundView).offset(-16);
            make.top.mas_equalTo(weakSelf.titleLabel.mas_bottom).offset(-10);
            make.height.mas_equalTo(weakSelf.titleLabel.text.length > 0 ?(size.height + 20):MAX((90), (size.height + 20)));
        }];
    }else {
        [self.textLabel mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.left.mas_equalTo(weakSelf.backgroundView).offset(16);
            make.right.mas_equalTo(weakSelf.backgroundView).offset(-16);
            make.top.mas_equalTo(weakSelf.titleLabel.mas_bottom).offset(5);
            make.height.mas_equalTo(0);
        }];
    }
    CGFloat textBottomOffset = self.titleLabel.text.length > 0 ?(10):(0);
    __weak TYAlertField * field;
    for (int i = 0; i < self.fieldArray.count; i ++) {
        [self.backgroundView addSubview:self.fieldArray[i]];
        if (i == 0) {
            [self.fieldArray[i] mas_remakeConstraints:^(MASConstraintMaker *make) {
                make.left.mas_equalTo(weakSelf.backgroundView).offset(30);
                make.right.mas_equalTo(weakSelf.backgroundView).offset(-30);
                make.height.mas_equalTo(45);
                make.top.mas_equalTo(weakSelf.textLabel.mas_bottom).offset(textBottomOffset);
            }];
        }else {
            [self.fieldArray[i] mas_remakeConstraints:^(MASConstraintMaker *make) {
                make.left.mas_equalTo(weakSelf.backgroundView).offset(30);
                make.right.mas_equalTo(weakSelf.backgroundView).offset(-30);
                make.height.mas_equalTo(45);
                make.top.mas_equalTo(field.mas_bottom).offset(10);
            }];
        }
        field = self.fieldArray[i];
    }
    
    __weak TYAlertAction * act;
    for (int i = 0; i < self.actionArray.count; i ++) {
        [self.backgroundView addSubview:self.actionArray[i]];
        if (self.actionArray.count == 2) {
            if (i == 0) {
                [self.actionArray[i] mas_remakeConstraints:^(MASConstraintMaker *make) {
                    make.left.mas_equalTo(weakSelf.backgroundView);
                    make.width.mas_equalTo(weakSelf.backgroundView).multipliedBy(0.5);
                    make.height.mas_equalTo(49);
                    if (field) {
                        make.top.mas_equalTo(field.mas_bottom).offset(24);
                    }else {
                        make.top.mas_equalTo(weakSelf.textLabel.mas_bottom).offset(textBottomOffset);
                    }
                    make.bottom.mas_equalTo(weakSelf.backgroundView);
                }];
                
                UIView * bottomLine = [[UIView alloc]init];
                bottomLine.backgroundColor = self.lineColor;
                [self.backgroundView addSubview:bottomLine];
                [bottomLine mas_makeConstraints:^(MASConstraintMaker *make) {
                    make.left.mas_equalTo(weakSelf.backgroundView);
                    make.right.mas_equalTo(weakSelf.backgroundView);
                    make.top.mas_equalTo(weakSelf.actionArray[i]);
                    make.height.mas_equalTo(0.5);
                }];
            }else {
                [self.actionArray[i] mas_remakeConstraints:^(MASConstraintMaker *make) {
                    make.left.mas_equalTo(act.mas_right);
                    make.width.mas_equalTo(weakSelf.backgroundView).multipliedBy(0.5);
                    make.height.mas_equalTo(49);
                    if (field) {
                        make.top.mas_equalTo(field.mas_bottom).offset(24);
                    }else {
                        make.top.mas_equalTo(weakSelf.textLabel.mas_bottom).offset(textBottomOffset);
                    }
                }];
                
                UIView * bottomLine = [[UIView alloc]init];
                bottomLine.backgroundColor = self.lineColor;
                [self.backgroundView addSubview:bottomLine];
                [bottomLine mas_makeConstraints:^(MASConstraintMaker *make) {
                    make.left.mas_equalTo(weakSelf.actionArray[i]);
                    make.top.bottom.mas_equalTo(weakSelf.actionArray[i]);
                    make.width.mas_equalTo(0.5);
                }];
            }
        }else {
            if (i == 0) {
                [self.actionArray[i] mas_remakeConstraints:^(MASConstraintMaker *make) {
                    make.left.mas_equalTo(weakSelf.backgroundView);
                    make.width.mas_equalTo(weakSelf.backgroundView);
                    make.height.mas_equalTo(49);
                    if (field) {
                        make.top.mas_equalTo(field.mas_bottom).offset(24);
                    }else {
                        make.top.mas_equalTo(weakSelf.textLabel.mas_bottom).offset(textBottomOffset);
                    }
                    if (i == weakSelf.actionArray.count - 1) {
                        make.bottom.mas_equalTo(weakSelf.backgroundView);
                    }
                }];
            }else {
                [self.actionArray[i] mas_remakeConstraints:^(MASConstraintMaker *make) {
                    make.left.mas_equalTo(weakSelf.backgroundView);
                    make.width.mas_equalTo(weakSelf.backgroundView);
                    make.height.mas_equalTo(49);
                    make.top.mas_equalTo(act.mas_bottom);
                    if (i == weakSelf.actionArray.count - 1) {
                        make.bottom.mas_equalTo(weakSelf.backgroundView);
                    }
                }];
            }
            
            UIView * bottomLine = [[UIView alloc]init];
            bottomLine.backgroundColor = self.lineColor;
            [self.backgroundView addSubview:bottomLine];
            [bottomLine mas_makeConstraints:^(MASConstraintMaker *make) {
                make.left.mas_equalTo(weakSelf.backgroundView);
                make.right.mas_equalTo(weakSelf.backgroundView);
                make.top.mas_equalTo(weakSelf.actionArray[i]);
                make.height.mas_equalTo(0.5);
            }];
        }
        act = self.actionArray[i];
    }
}

- (void)viewDidLayoutSubviews {
    [super viewDidLayoutSubviews];
    CGFloat height = 0;
    [self.backgroundView layoutIfNeeded];
    for (UIView * view in self.backgroundView.subviews) {
        if (CGRectGetMaxY(view.frame) > height) {
            height = CGRectGetMaxY(view.frame);
        }
    }
    if (self.fieldArray.count > 0) {
        [self.fieldArray[0]becomeFirstResponder];
    }
    __weak typeof(self) weakSelf = self;
    [self.backgroundView mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.centerX.centerY.mas_equalTo(weakSelf.view);
        make.left.mas_equalTo(36);
        make.right.mas_equalTo(-36);
//        make.height.mas_equalTo(height);
    }];
}

@end

@implementation TYAlertAction
+ (instancetype)actionWithTitle:(NSString *)title type:(TYAlertActionType)type clickComplete:(void(^)(TYAlertAction * action))complete {
    TYAlertAction * action = [[TYAlertAction alloc]init];
    [action setTitle:title forState:(UIControlStateNormal)];
    [action addTarget:action action:@selector(clickComplete) forControlEvents:(UIControlEventTouchUpInside)];
    action.complete = complete;
    if (type == TYAlertActionType_default) {
        action.titleColor = [UIColor colorWithHex:0xffffff];
        
    }else if (type == TYAlertActionType_redTitle) {
        action.titleColor = [UIColor colorWithHex:0xff2857];
        
    }else{
        action.titleColor = [UIColor colorWithHex:0x323233];
    }
    action.titleLabel.font = [UIFont systemFontOfSize:14];
    return action;
}

- (void)clickComplete {
    BOOL isEnd = YES;
    if (self.shouldComplete) {
        isEnd = self.shouldComplete(self);
    }
    __weak typeof(self) weakSelf = self;
    if (isEnd) {
        [self.targetVC dismissViewControllerAnimated:NO completion:^{
            if (self.complete) {
                self.complete(self);
            }
        }];
        
    }
}

- (void)setTitleColor:(UIColor *)titleColor {
    _titleColor = titleColor;
    [self setTitleColor:titleColor forState:(UIControlStateNormal)];
}
@end


@implementation TYAlertField
+ (instancetype)actionWithText:(NSString *)text placeHolder:(NSString *)placeHolder textChange:(void(^)(TYAlertField * action))complete {
    TYAlertField * action = [[TYAlertField alloc]init];
    action.textColor = [UIColor colorWithHex:0x000000];
    action.complete = complete;
    action.placeholder = placeHolder;
    action.font = [UIFont systemFontOfSize:13];
    //    action.layer.borderColor = [UIColor colorWithHex:0xDCDDE0].CGColor;
    //    action.layer.borderWidth = 0.5;
    action.layer.cornerRadius = 2;
    action.backgroundColor = [UIColor colorWithHex:0xf4f4f4];
    action.leftView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 10, 45)];
    action.leftViewMode = UITextFieldViewModeAlways;
    [[NSNotificationCenter defaultCenter]addObserver:action selector:@selector(textFieldDidChange:) name:UITextFieldTextDidChangeNotification object:nil];
    return action;
}

- (void)textFieldDidChange:(NSNotification *)noty {
    if (noty.object == self) {
        if (self.complete) {
            self.complete(self);
        }
    }
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter]removeObserver:self];
}
/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
